package com.woodws.core.interceptor;

import com.woodws.core.annotation.I18n;
import com.woodws.core.util.I18nUtil;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by maoxiaodong on 2016/10/28.
 */
public class WebInterceptor extends HandlerInterceptorAdapter {


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            modelAndView.addObject("ctx", request.getContextPath());
        }

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(I18n.class)) {
                I18n i18n = method.getAnnotation(I18n.class);
                String[] values = i18n.value();
                Map<String, Object> map = modelAndView.getModel();
                I18nUtil i18nUtil = new I18nUtil(getWebApplicationContext(request));
                for (String value : values) {
                    i18nUtil.escapeLanguage(map, value);
                }
            }
        }
    }

    private WebApplicationContext getWebApplicationContext(HttpServletRequest request) {
        return WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
    }
}
